var lang = i18n.name;
var userType = getUT();
$(document).ready(function() {
    
    $('#tickAll').attr("checked", false);
    
    var userType = getUT();
    if(userType != undefined && userType == "1"){
        $("#filter").css({"display" : ""});
        $("#_header2_send_waybill_his").parent().css("display","none");
        $("#_header2_rec_waybill_his").parent().css("display","none");
        $("#_header2_export_waybill").parent().css("display","none");
    }
    
	// 绑定弹出事件-添加运单号（弹出层）
	bindEvt4addWaybillNo();

	// 绑定校验规则-表单（form_addWaybillNo）
	bindValidation4addWaybillNo();

	// 绑定收缩事件-查看运单列表
	bindEvt4showWaybillList();

	$('#tickAll').click(function() {
		var isChecked = this.checked;
		$('input[type="checkbox"]').each(function(i, item) {
			this.checked = isChecked;
		});
	});
	$('#batchCancel').click(function() {
	    var flag = true;
	    //判断是否可以取消订单
	    $('input[type=checkbox]:checked').not("#tickAll").not("#cb_orderStatus_all").not("input[name='cb_orderStatus']").each(function(i, item){
            var order = eval("(" + item.value + ")");
	        if(!isInnerOrder(order)){
	        	 sfAlert(i18n.myorder_innerorder_wrong);
		           flag = false;
		           return ;
	        }
            if(!canCancel(order)){
	           sfAlert(i18n.myorder_cancel_wrong);
	           flag = false;
	           return ;
	        }
	    });
	    if(!flag){
	        return ;
	    }
	    
		update(getOrderNos("CANCEL"), "CANCEL", "BATCH");
	});
	$('#batchUrge').click(function() {
	    var flag = true;
        //判断是否可以催收订单
        $('input[type=checkbox]:checked').not("#tickAll").not("#cb_orderStatus_all").not("input[name='cb_orderStatus']").each(function(i, item){
            var order = eval("(" + item.value + ")");
            if(!canUrge(order)){
               sfAlert(i18n.myorder_urge_wrong);
               flag = false;
               return ;
            }
        });
        if(!flag){
            return ;
        }
		update(getOrderNos("URGE"), "URGE", "BATCH");
	});
	$('#batchDelete').click(function() {
	    var flag = true;
	    //判断是否可以删除订单
        $('input[type=checkbox]:checked').not("#tickAll").not("#cb_orderStatus_all").not("input[name='cb_orderStatus']").each(function(i, item){
            var order = eval("(" + item.value + ")");
            //非次日已受理和非已取件和非已取消的订单不能删除
            if(!canDelete(order)){
               sfAlert(i18n.myorder_delete_wrong);
               flag = false;
               return ;
            }
        });
        if(!flag){
            return ;
        }
		update(getOrderNos("DELETE"), "DELETE", "BATCH");
	});
	$('#btnQuery').click(function() {
		resetPageInfo();
		getMyOrders('','','');
	});
	
	$("#orderFilter").change(function(){
	    var ot = $("#orderFilter").val();
	    getMyordersByOrderType(ot);
	});
	
	getMyordersByOrderType($("#orderFilter").val());
	
	
	
	
	
	
	
	
	
	/******查询订单******/
	$("#queryOrder").click(function(){
		$('#orderFilter').val('ALL');
		$('#orderFilter').render();
		var orderStatus='';
		$('input:checkbox[name="cb_orderStatus"]:checked').each(function(){
			orderStatus += "'"+$(this).val()+"',";
		});
		var startTm =  $("#startTm").val();
		var endTm = $("#endTm").val();
		if(startTm != '' && endTm != ''){
			if(startTm > endTm){
				sfAlert(i18n.beginTM_gt_endTM_error);
				$("#startTm").val('');
				$("#endTm").val('');
				return;
			}
		}
		$("#pageNo").val(1);
		getMyOrders(orderStatus,startTm,endTm);
	});
	
	var check_status = true;
	$("#cb_orderStatus_all").click(function(){
		if(check_status){
			$(this).attr("checked",!check_status);
			$('input:checkbox[name="cb_orderStatus"]').each(function(){
				$(this).attr("checked",!check_status);
			});
			check_status = false;
		}else{
			$(this).attr("checked",!check_status);
			$('input:checkbox[name="cb_orderStatus"]').each(function(){
				$(this).attr("checked",!check_status);
			});
			check_status = true;
		}
	});
	
	$("input[name='cb_orderStatus']").click(function(){
		var check_status = this.checked;
		if(check_status == false){
			$("#cb_orderStatus_all").attr("checked",false);
			check_status = false;
		}
		this.checked = check_status;
	});
	
	
});


function getMyordersByOrderType(ot){
    if(ot != undefined && ot != ''){
        if(ot == "ALL"){
            resetPageInfo();
            getMyOrders('','','');
        } else{
            var url = "/service/order/myorder/" + ot;
            var type = "get";
            var dataType = 'json';
            var data = $("#myOrdersForm").serialize();
            
            asyncCallService(url, type, dataType, data, function(data) {
        
                var myOrdersTable = $("#divMyOrders");
        
                myOrdersTable.empty();
        
                // 如果没有记录，显示无记录页面
                if(data.result == null){
                    showNoOrderRecord();
                    return;
                }
            	$("#myorder_norecord_div").hide();
                $("#myorder_record_div").show();
                var tr = '<table width="100%" cellspacing="0" cellpadding="0">'+
                			'<colgroup>'+
                				'<col width="30" />'+
                				'<col width="130" />'+
                				'<col width="130" />'+
                				'<col width="90" />'+                				
                				'<col width="90" />'+
                				'<col width="130" />'+
                				'<col width="" />'+
                			'</colgroup>';
	
                $.each(data.result, function(i, item) {
                    
                    var orderStateCodeStr = os_i18n.get(item.orderStateCode);
                    var bookingtime = '';
                    if(item.isBooking == '1'){
                        bookingtime = getI18nFormatDateByLong(parseInt(item.bookingTime),true);
//                        orderStateCodeStr = orderStateCodeStr + '('+ i18n.myorder_booking_time + bookingtime + ')';
                    }
                    
                    var orderSource = '';
            		if(item.orderSource == '13') {
            			orderSource = i18n.orderSource_android;
            		} else if(item.orderSource == '14') {
            			orderSource = i18n.orderSource_iphone;
            		} else if(item.orderSource == '15') {
            			orderSource = 'WAP';
            		} else if(item.orderSource == '16') {
            			orderSource = 'mobilePhone';
           			} else if(item.orderSource == '18') {
            			orderSource = 'JME';
            		} else if(item.orderSource == '19') {
            			orderSource = i18n.orderSource_webserver_history;
            		} else if(item.orderSource == '20') {
            			orderSource = i18n.orderSource_webserver_sync;
            		} else if(item.orderSource == '21') {
            			orderSource = i18n.orderSource_weixin_order;
            		} else {
            			orderSource = i18n.orderSource_web_order;
            		}
                    


                    var gen_OpCol = '';
                    if(!(userType == '1' && item.orderType=="6")){
                        gen_OpCol = genOpCol(item);
                    } else {
                        gen_OpCol = genOpColForInner(item);
                    }
                   	tr = tr + '<tr onMouseOver="onMouseHoverTr(this);" onMouseOut="onMouseOutTr(this);" onClick="trOnClick(this);">'+
                                  '<td class="first"><input type="checkbox" name="" value=/></td>'+
                                 // '<td><a href="#">'+item.orderNo+'</a></td>'+
								 '<td><a onclick=\'javascript:queryDetail("'+ item.orderNo + '","' + item.orderType + '","' + item.orderState + '");\'>'+item.orderNo+'</a></td>'+
                                  '<td>'+item.orderTm4Dispaly+'</td>'+
                                  '<td>'+orderSource+'</td>'+                                  
                                  '<td>'+orderStateCodeStr+'</td>'+                                  
                                  '<td>'+bookingtime+'</td>'+
                                  '<td>' + gen_OpCol + '</td>'+
                               '</tr>';
        
                });
                
                myOrdersTable.html(tr+'</table>');
        
                $("#pagingBar").empty();
        
                var totalCount = data.totalCount;
                if (totalCount > 0) {
                    $("#pagingBar").append(data.pagingBar);
                } else {
                    showNoOrderRecord();
                }
            }, function() {
                showNoOrderRecord();
            });
        }
    }    
}

//表格行鼠标移上去高亮
function onMouseHoverTr(id){
	$(id).addClass("hover");
}

function onMouseOutTr(id){
	$(id).removeClass("hover");
}

//表格行点击变色
function trOnClick(id){
	if ($(id).hasClass("selected")) {
		$(id).removeClass("selected").find(":checkbox").attr("checked",false);
	}else{
		$(id).addClass("selected").find(":checkbox").attr("checked",true);
	}
}

/**
 * 重置分页信息
 */
function resetPageInfo() {
	$("#pageNo").val('');
	$("#pageSize").val('');
}

/**
 * 为查看运单列表绑定收缩事件
 */
function bindEvt4showWaybillList() {
	$('.myorder_up').live(
			'click',
			function() {
				$(".myorder_up").toggle(
						function() {

							$(this).addClass("myorder_up2");

							$(this).closest(".myorder_num").find(
									".myorder_list").slideToggle();

						},
						function() {

							$(this).closest(".myorder_num").find(
									".myorder_list").slideToggle();

							$(this).removeClass("myorder_up2");

						});
			});
}

/**
 * 为表单（form_addWaybillNo）绑定校验规则，
 */
function bindValidation4addWaybillNo() {
	// 验证
	$("#form_addWaybillNo")
			.Validform(
					{
						tiptype : function(msg, o, cssctl) {
							if (!o.obj.is("form")) {
								var objtip = o.obj.parents().children(
										".Validform_checktip");
								cssctl(objtip, o.type);
								objtip.text(msg);
							}
						},
						datatype : {
							"rmobile" : function(gets, obj, curform, regxp) {
								var reg1 = regxp["n"], reg2 = regxp["m"], phone = $("#mobilephone");
								if (reg1.test(phone.val())) {
									if (gets != '') {
										return reg2.test(gets);
									}
									return true;
								}
								if (reg2.test(gets)) {
									return true;
								}
								return false;
							},
							"r_bno" : function(gets, obj, curform, regxp) {
								var digit = /^\d{12}$/;
								if (!digit.test(obj.val())) {
									return i18n.myorder_waybillno_invalid;
								} /*else {
									var response = "";

									var url = "/service/order/checkOrderWaybillExists";
									var type = "POST";
									var dataType = 'JSON';
									var data = {
										"orderNo" : $("#orderNo").val(),
										"bno" : obj.val()
									};

									syncCallService(url, type, dataType, data,
											function(result) {
												// console.log(result);
												// console.log(result.isExists);
												if (true == result.isExists) {
													response = "已经添加过该运单号";
												}
											}, function(result) {
												// console.log(result);
											});

									if (response != "") {
										return response;
									}
								}*/
							}
						},
						ajaxPost : true,
						callback : function(data) {

							var flag = data.flag;

							if ("success" == flag) {

								addBnoDialog.close();

								var orderNo = $("#orderNo").val();

								var divOrder = $("div[id='" + orderNo + "']");
								divOrder.empty();

								var waybillList = data.info.waybillList;
								var waybillListHtml = buildWaybillList(waybillList);
								divOrder.append(waybillListHtml);
								divOrder.css("display", "block");

								var showWb = buildShowWaybillList(data.info);
								var p = $("p[id='p_" + orderNo + "']");
								p.empty();
								p.append(showWb);
								sfAlert(i18n.myorder_add_waybillno_success);
								addBnoDialog.close();

							} else if ("fail" == flag) {
								sfAlert(i18n.myorder_add_waybillno_fail);
							} else if("alreadyExists" == flag){
                                sfAlert(i18n.myorder_add_waybillno_exist);
							} else if("alreadyUsed" == flag){
							    sfAlert(i18n.myorder_add_waybillno_used);
							}
						}
					});
}

/**
 * 为“添加运单号”链接绑定事件
 */
function bindEvt4addWaybillNo() {

	$('.myorder_num_box').live('click', function() {
		$("#tipSpan").empty();
		$("#tipSpan").attr("class", "Validform_checktip");
		$("#orderNo").val(this.id);
		$("#bno").val("");
		addBnoDialog = art.dialog({
			title : i18n.myorder_add_waybillno,
			padding : 0,
			lock : true,
			background : "#444",
			content : document.getElementById('myorder_add')
		});

		$("#bno").focus();
	});
}

/** 获取我的快件 */
function getMyOrders(orderStatus,startTm,endTm) {
	
	if (orderStatus == undefined) {
		orderStatus='';
		$('input:checkbox[name="cb_orderStatus"]:checked').each(function(){
			orderStatus += "'"+$(this).val()+"',";
		});
	}
	if (startTm == undefined) {
		startTm =  $("#startTm").val();
	}
	if (endTm == undefined) {
		endTm = $("#endTm").val();
	}

	var url = "/service/order/myorder?orderStatus="+orderStatus+"&startTm="+startTm+"&endTm="+endTm;
	var type = "get";
	var dataType = 'json';
	var data = $("#myOrdersForm").serialize();
	
	asyncCallService(url, type, dataType, data, function(data) {

		var myOrdersTable = $("#divMyOrders");

		myOrdersTable.empty();

		// 如果没有记录，显示无记录页面
		if(data.result == null){
			showNoOrderRecord();
			return;
		}
		$("#myorder_norecord_div").hide();
        $("#myorder_record_div").show();
		var tr = '<table width="100%" cellspacing="0" cellpadding="0">'+
                			'<colgroup>'+
                				'<col width="30" />'+
                				'<col width="130" />'+
                				'<col width="130" />'+
                				'<col width="90" />'+               				
                				'<col width="90" />'+
                				'<col width="130" />'+
                				'<col width="" />'+
                			'</colgroup>';
	
		$.each(data.result, function(i, item) {
                    
			var orderStateCodeStr = os_i18n.get(item.orderStateCode);
			var bookingtime = '';
            if(item.isBooking == '1'){
				bookingtime = getI18nFormatDateByLong(parseInt(item.bookingTime),true);
//                orderStateCodeStr = orderStateCodeStr + '('+ i18n.myorder_booking_time + bookingtime + ')';
            }
            
            var orderSource = '';
            if(item.orderSource == '13') {
            	orderSource = i18n.orderSource_android;
            } else if(item.orderSource == '14') {
            	orderSource = i18n.orderSource_iphone;
            } else if(item.orderSource == '15') {
            	orderSource = 'WAP';
            } else if(item.orderSource == '16') {
            	orderSource = 'mobilePhone';
            } else if(item.orderSource == '18') {
            	orderSource = 'JME';
            } else if(item.orderSource == '19') {
            	orderSource = i18n.orderSource_webserver_history;
            } else if(item.orderSource == '20') {
            	orderSource = i18n.orderSource_webserver_sync;
            } else if(item.orderSource == '21') {
            	orderSource = i18n.orderSource_weixin_order;
            } else {
            	orderSource = i18n.orderSource_web_order;
            }
            
            var gen_OpCol = '';
            if(!(userType == '1' && item.orderType=="6")){
				gen_OpCol = genOpCol(item);
            } else {
                gen_OpCol = genOpColForInner(item);
            }
            var itemStr = objToJsonStr(item);
            tr = tr + '<tr onMouseOver="onMouseHoverTr(this);" onMouseOut="onMouseOutTr(this);" onClick="trOnClick(this);">'+
						'<td class="first"><input type="checkbox" name="" value="' + itemStr + '"/></td>'+
                        '<td><a onclick=\'javascript:queryDetail("'+ item.orderNo + '","' + item.orderType + '","' + item.orderState + '");\'>'+item.orderNo+'</a></td>'+
                        '<td>'+item.orderTm4Dispaly+'</td>'+
                        '<td>'+orderSource+'</td>'+
                        '<td>'+orderStateCodeStr+'</td>'+                                            
                        '<td>'+bookingtime+'</td>'+
                        '<td>' + gen_OpCol + '</td>'+
                      '</tr>';
        
         });
                
        myOrdersTable.html(tr+'</table>');

		$("#pagingBar").empty();

		var totalCount = data.totalCount;
		if (totalCount > 0) {
			$("#pagingBar").append(data.pagingBar);
		} else {
			showNoOrderRecord();
		}
	}, function() {
		showNoOrderRecord();
	});
}

/**
 * 构建显示运单列表的三角箭头
 * 
 * @param item
 * @returns {String}
 */
function buildShowWaybillList(item) {
	var waybillList = item.waybillList;
	if (null != waybillList && waybillList.length > 0) {
		return '<a id="showWaybill_' + item.orderNo
				+ '" class="unl fr ml10 myorder_up"></a>';
	} else {
		return "&nbsp;";
	}

}

/**
 * 构建订单详情链接
 * 
 * @param item
 */
function buildOrderDetailLink(item) {
	var goto_order_detail = '';
	if(userType =='0'){
		goto_order_detail = '(' + i18n.myorder_goto_order_detail + ')';
	}
	
	var link = "      <span class=\"ml20\">" + '<a' + '        class="unl hot"'
			+ '        onclick=\'javascript:queryDetail("'
			+ item.orderNo + '","' + item.orderType + '","' + item.orderState + '");\'>' + i18n.myorder_order_detail + '</a>' + 
			goto_order_detail+
			'</span>';

	var l = getL();
	if (2 == l || true == item.hasOprRight) {
		return link;
	} else {
		return "&nbsp;";
	}
}

/**
 * 显示“没有订单记录”，并给出我要下单链接
 */
function showNoOrderRecord() {
	
	var linkStr = (1 == getUT()) ?'/'+i18n.name+ '/innerorder/inner_discount_order.html' 
			: ('0' == isCustMem()) ?'/'+i18n.name+ '/order/order.html' :'/'+i18n.name+  '/order/batch_order.html';
	$("#myorder_record_div").hide();
	$("#myorder_norecord_div").empty();
	$("#myorder_norecord_div").append(
			'<p class="txt1 pt50 pb50 tc">' + i18n.myorder_no_record + '&nbsp;&nbsp;<a href="' + linkStr
					+ '" class="unl">' + i18n.myorder_place_order + '</a></p>');
	$("#myorder_norecord_div").show();
}

/**
 * 构建运单列表
 * 
 * @param waybillList
 * @returns {String}
 */
function buildWaybillList(waybillList) {

	var str = '<ul>';

	if (null != waybillList && waybillList.length > 0) {
		for ( var i = 0; i < waybillList.length; i++) {
			var item = waybillList[i];
			str += buildWaybill(item);
		}
	}
	str += "</ul>";

	return str;
}

/**
 * 构建运单
 * 
 */
function buildWaybill(item) {

	var str = '      <li>'
			+ "        <div class=\"myorder_detail_tit2 clearfix\">"
			+ "          <span class=\"fl\"><strong>" + i18n.myorder_waybillno +  "</strong>："
			+ ((null == item.bno) ? "&nbsp;" : item.bno)
			+ "</span>"
			+ "          <span class=\"ml30 fl\"><strong>" + i18n.myorder_recipient + "</strong>："
			+ ((null == item.receiver) ? "&nbsp;" : item.receiver)
			+ "</span> 																											"
			+ "<span"
			+ "            class=\"fr mr10\"> <a"
			+ "            class=\"unl hot mr5\""
			+ "            href=\"http://www.sf-express.com/cn/sc\">" + i18n.myorder_trace + "</a> <a"
			+ "            class=\"unl hot\""
			+ "            href=\"/subscription/"+ i18n.name + "/mail_subscription.html\">" + i18n.myorder_email_rss + "</a>"
			+ "          </span>"
			+ "        </div>"
			+ "      </li>"
			+ "      <li>"
			+ "        <div class=\"myorder_detail_tit3 clearfix\">"
			+ "          <span class=\"fl myorder_sender\"><strong>" + i18n.myorder_position + "</strong><br>"
			+ "            <b class=\"f22\">"
			+ ((null == item.loaction) ? "&nbsp;" : item.loaction)
			+ "</b></span> <span class=\"ml30 fl\"><strong>" + i18n.myorder_state + "</strong><br>"
			+ "            <b class=\"f22\">"
			+ ((null == item.state4Display) ? "&nbsp;" : item.state4Display)
			+ "</b></span>"
			+ buildCancelRelativedWaybill(item)
			+ "        </div>																									"
			+ "      </li>																										";
	return str;
}

/**
 * 构建取消关联运单链接
 * 
 * @param waybillType
 *            运单类型
 * @returns {String} 取消关联运单链接
 */
function buildCancelRelativedWaybill(item) {
	if ("U" == item.waybillType) {
		return '<span class="fr mt10 mr10"><a class="unl hot f14" onclick="javascript:cancelRelativedWaybill(\''
				+ item.orderNo + '\',\'' + item.bno + '\');">' + i18n.myorder_cancel_relative_waybillno + '</a></span>';
	} else {
		return "";
	}
}

/**
 * 取消关联运单
 * 
 * @param item
 */
function cancelRelativedWaybill(orderNo, bno) {
	var msg = i18n.myorder_confirm_cancel_relative_waybillno + bno + "？";
	sfConfirm(msg, function() {
		var url = "/service/order/myorder/waybill/" + orderNo + "/" + bno;
		var type = "delete";
		var dataType = 'JSON';
//		var data = {
//			"orderNo" : orderNo,
//			"bno" : bno
//		};
		asyncCallService(url, type, dataType, null, function(data) {
			var waybillList = data.info.waybillList;
			$("div[id='" + orderNo + "']").empty();
			if (null != waybillList && waybillList.length > 0) {
				var waybillListHtml = buildWaybillList(data.info.waybillList);
				$("div[id='" + orderNo + "']").append(waybillListHtml);
			} else {
				$("a[id='showWaybill_" + orderNo + "']").remove();
			}
		}, function() {
			sfConfirm(i18n.myorder_user_timeout, function() {
    			login();
            }, function() {
            });
		});
	}, function() {
	});
}

/**
 * 对象转化成JOSN格式的字符串
 * 
 * @param obj
 *            对象
 * @returns {String} JOSN格式的字符串
 */
function objToJsonStr(obj) {
	var isFirstEle = true;
	var result = "{";
	for ( var i in obj) {
		if (isFirstEle) {
			isFirstEle = false;
		} else {
			result += ",";
		}
		var val = (null == obj[i] || "null" == obj[i]) ? "" : obj[i];
		result += "'" + i + "':'" + val + "'";
	}
	result += "}";
	return result;
}

/**
 * 
 * 
 * 
 * 生成操作列信息
 */
function genOpCol(item) {
	
	var opCol = '<span class="btn-group">';

	var l = getL();
	if (2 == l || true == item.hasOprRight) {
		// 取件
		if ("5" == item.orderStateCode) {
			/*opCol += '<a class="ui-btn btn-normal myorder_num_box" id="' + item.orderNo + '"><span class="ui-btn-txt">' 
					+ i18n.myorder_add_waybillno + '</span></a>';*/
		}
		// 催收
		if ("1" == item.orderStateCode || "3" == item.orderStateCode
				|| "6" == item.orderStateCode) {

			if (item.overHours >= 1) {// 已下单超过1小时
				if (item.isInReserveTm == false || item.overDays >= 1 || !canUrge(item)) {// 已下单超过1天、超过服务时间
					// 不能催收，只能催收当日订单
				} else {
					opCol += '<a class="ui-btn btn-normal" onclick=\'javascript:update("'
							+ item.orderNo
							+ '","URGE","SINGLE");\'><span class="ui-btn-txt">' + i18n.myorder_urge + '</span></a>';
				}
			}
		}

		// 取消
		if ("0" == item.orderStateCode || "1" == item.orderStateCode
				|| "6" == item.orderStateCode || "3" == item.orderStateCode) {
			if (item.overDays >= 1 || !canCancel(item)) {// 次日不能消单
				// 
			} else {
				opCol += '<a class="ui-btn btn-normal" onclick=\'javascript:update("'
						+ item.orderNo
						+ '","CANCEL","SINGLE");\'><span class="ui-btn-txt">' + i18n.myorder_cancel + '</span></a>';
			}
		}

		// 非已取件的次日订单、已取件、已取消
		if ((item.overDays >= 1 && "5" != item.orderStateCode) || "5" == item.orderStateCode || "7" == item.orderStateCode) {
			opCol += '<a class="ui-btn btn-normal" onclick=\'javascript:update("'
					+ item.orderNo
					+ '","DELETE","SINGLE")\'><span class="ui-btn-txt">' + i18n.myorder_delete + '</span></a>';
		}

		/* 删除:已受理的订单次日可以删除
		if (item.overDays >= 1) {
			if ("0" == item.orderStateCode || "1" == item.orderStateCode
					|| "2" == item.orderStateCode || "3" == item.orderStateCode) {
				opCol += '<a class="ml5 ui-btn btn-mingray" onclick=\'javascript:update("'
						+ item.orderNo
						+ '","DELETE","SINGLE")\'><span class="ui-btn-txt">删除</span></a>';
			}
		}*/
	}

	opCol += "</span>";

	return opCol;
}

function genOpColForInner(item){
	var opCol = '<span class="btn-group">';
    
    var l = getL();

    if (2 == l || true == item.hasOprRight) {
        // 内部件
        if ("5" == item.orderStateCode || "0" == item.orderStateCode || "6" == item.orderStateCode) {
            opCol += '<a class="ui-btn btn-normal" onclick=\'javascript:update("'
                    + item.orderNo
                    + '","DELETE","SINGLE")\'><span class="ui-btn-txt">' + i18n.myorder_delete + '</span></a>';
        }
    }

    opCol += "</span>";

    return opCol;
}

/**
 * 更新订单
 */
function update(orderNos, action, actionType) {

	if (actionType === "BATCH") {
		var hasSelectedItems = checkSelected();
		if (!hasSelectedItems) {
			sfAlert(i18n.myorder_select_order_empty);
			return;
		}
	}

	var act = "";// 操作

	if ("CANCEL" === action) {
		act = i18n.myorder_action_cancel;
	}
	if ("DELETE" === action) {
		act = i18n.myorder_delete;
	}
	if ("URGE" === action) {
		act = i18n.myorder_urge;
	}
	if ("REPRINT_WAYBILL" === action) {
		act = i18n.myorder_action_print;
	}
	if ("SUBSCRIBE_MAIL" === action) {
		act = i18n.myorder_email_rss;
	}
	if ("MODIFY" === action) {
		act = i18n.myorder_action_modify;
	}

	var isTrans = isTransgender();

	if (isTrans) {
		sfConfirm(i18n.myorder_transgener_user, function() {
			window.location.href = "/user/" + i18n.name + "/passw_sentphone.html";
		}, function() {
			//
		});
	}

	if (isTrans) {
		return;
	}
	if (actionType === "BATCH") {
		if (!orderNos || orderNos.length === 0) {
			sfAlert(i18n.myorder_select_order_empty);
		} else {
			sfConfirm(i18n.myorder_confirm_action + act + i18n.myorder_confirm_operate_selected_record + "<BR/>"
					+ wordwrapOrderNos(orderNos), function() {
				updateMyOrders(orderNos, action, actionType, act);
			}, function() {
				//
			});
		}
	} else if (actionType === "SINGLE") {
		sfConfirm(i18n.myorder_confirm_action + act + i18n.myorder_dot + " " + i18n.myorder_orderno + "<BR/>" + orderNos + "？", function() {
			updateMyOrders(orderNos, action, actionType, act);
		}, function() {
			//
		});
	}
}

/**
 * 更新我的订单
 * 
 * @param orderNos
 *            订单号
 * @param action
 *            操作
 */
function updateMyOrders(orderNos, action, actionType, act) {

	var url = '/service/order/myorder/' + action + '/' + orderNos;
	var type = "POST";
	var dataType = 'JSON';
	asyncCallService(url, type, dataType, null, function(data) {
		if ("1" == data.status) {
			if (actionType === "BATCH") {
				sfAlert(i18n.myorder_action_success + act + i18n.myorder_dot);
			} else if (actionType === "SINGLE") {
				sfAlert(i18n.myorder_order + orderNos + i18n.myorder_have_success + act + i18n.myorder_dot);
			}
			resetPageInfo();
			getMyordersByOrderType($("#orderFilter").val());
		} else if("2" == data.status){
			var orders = "";
			$.each(data.failOrders, function(i, item) {
				orders += "<BR/>" + item;
			});
			orders += "<BR/>";
		    sfAlert(i18n.myorder_have_select + orders + i18n.myorder_have_fail + 
		    		act + i18n.myorder_operate_again);
		} else if("4"==data.status){
			if("err06"==data.errorcode){
				sfAlert("很抱歉，由于订单揽收过程中出现异常，详情请致电95338咨询");
			}else{
				sfAlert(i18n.myorder_have_fail + act + i18n.myorder_operate_again);
			}
			
		}else {
			sfAlert(i18n.myorder_have_fail + act + i18n.myorder_operate_again);
		}
	}, function() {
		sfConfirm(i18n.myorder_user_timeout, function() {
            login();
        }, function() {
        });
	});
}

/**
 * 获取选中的订单
 */
function getOrderNos(action) {
	var orderNos = "";
	$('input[type=checkbox]:checked').not("#tickAll").not("#cb_orderStatus_all").not("input[name='cb_orderStatus']").each(function(i, item){

				var itemJson = eval("(" + item.value + ")");

				/*if (this.checked) {

					var ordersState = itemJson.orderStateCode;

					if ("CANCEL" === action) {// 取消
						if ("0" === ordersState || "1" === ordersState
								|| "2" === ordersState || "3" === ordersState) {
							if (itemJson.overDays >= 1) {// 次日不能消单
								return true;// continue
							} else {
								// 可以取消
							}
						} else {
							return true;// 返回 'true'
							// 跳至下一个循环(就像在普通的循环中使用'continue')。
						}
					} else if ("URGE" === action) {// 催收

						if (itemJson.overHours >= 1) {// 已下单超过1小时
							if (itemJson.overDays >= 1) {// 已下单超过1天
								return true;// 跳过，只能催收当日订单
							} else {
								if ("0" === ordersState || "1" === ordersState
										|| "2" === ordersState
										|| "3" === ordersState
										|| "6" === ordersState) {
									// 可以催收
								} else {
									return true;
								}
							}
						} else {// 下单未超过1小时
							return true;
						}
					} else if ("DELETE" === action) {// 删除
						if ("5" === ordersState || "7" === ordersState) {
							// 可以删除
						} else {
							if (item.overDays >= 1) {
								if ("0" == item.orderStateCode
										|| "1" == item.orderStateCode
										|| "2" == item.orderStateCode
										|| "3" == item.orderStateCode) {
									// 已受理的订单次日可以删除
								}
							}

							return true;
						}
					}*/

					if (!orderNos) {
						orderNos = itemJson.orderNo;
					} else {
						orderNos += "," + itemJson.orderNo;
					}
				});
	return orderNos;
}

/**
 * 检查是否有选中项
 */
function checkSelected() {
	var hasSelectedItems = false;
	$('input[type="checkbox"]').not("#tickAll").not("#cb_orderStatus_all").not("input[name='cb_orderStatus']").each(function(i, item) {
		if (this.checked) {
			hasSelectedItems = true;
			return true;
		}
	});
	return hasSelectedItems;
}

/**
 * 
 * 0 未登录
 * 
 * 1 亚登录、有历史记录
 * 
 * 2 登录
 * 
 * 3 亚登录、没有历史记录
 * 
 * 
 * 检查用户是否为亚登录用户。
 */
function isTransgender() {

	var L = getL();

	if (1 == L || 3 == L) {
		return true;
	} else {
		return false;
	}

}

/**
 * 
 * 0 未登录
 * 
 * 1 亚登录、有历史记录
 * 
 * 2 登录
 * 
 * 3 亚登录、没有历史记录
 * 
 * 
 * 是否未登录。
 */
function isNoLogin() {

	var L = getL();

	if (0 == L) {
		return true;
	} else {
		return false;
	}

}

/**
 * 订单号换行
 * 
 * @param orderNos
 */
function wordwrapOrderNos(orderNos) {

	if (null == orderNos || "undefined" == orderNos || orderNos.length == 0) {
		return "";
	}

	var tmp = "";

	var aOrderNo = orderNos.split(",");
	for ( var i = 0; i < aOrderNo.length; i++) {
		if (i == 0) {
			tmp += aOrderNo[i];
		} else {
			tmp += "<BR/>" + aOrderNo[i];
		}
	}

	return tmp;
}

/**
 * 查询订单详情
 */
function queryDetail(orderNo,ot,orderState) {
	if (orderNo.indexOf("***") >= 0 && isTransgender()) {
		sfConfirm(i18n.myorder_transgener_user, function() {
			window.location.href = "/" + i18n.name
					+ "/user/passw_sentphone.html";
		}, function() {
		});
	} else {
		if("11"==ot || "12"==ot){
			window.location.href = '/' + i18n.name + '/order/myorderCHA_detail.html?orderNo=' + orderNo + '&ot=' + ot;
		}else{
			asyncCallService('/service/order/myorder/isbatch/' + orderNo, 'get', 'json', '', function(data){
				if(data == "y"){
					if(orderState != undefined && orderState != "5" && orderState != "6" && orderState != "7"){
						window.location.href = '/' + i18n.name + '/order/bthmyorder_detail.html?orderNo=' + orderNo + '&ot=' + ot;
					} else {
						window.location.href = '/' + i18n.name + '/order/bth_detail.html?orderNo=' + orderNo + '&ot=' + ot;
					}
				}else if(data == "n"){
					if("6"==ot){//内部公司件
						if(orderState != undefined && orderState != "5" && orderState != "6" && orderState != "7"){
							window.location.href = '/' + i18n.name + '/order/bthmyorder_detail.html?orderNo=' + orderNo + '&ot=' + ot;
						} else {
							window.location.href = '/' + i18n.name + '/order/bth_detail.html?orderNo=' + orderNo + '&ot=' + ot;
						}	
					}else{
						window.location.href = '/' + i18n.name + '/order/myorder_detail.html?orderNo=' + orderNo + '&ot=' + ot;
					}
				}else if(data == "MED"){
					window.location.href = '/' + i18n.name + '/order/myorder_med_detail.html?orderNo=' + orderNo + '&ot=' + ot+'&tp=Me';
				}
			},function(data){});
		}
	}
}


function isInnerOrder(order){
	//内部件
    if(order.orderType=="6"){
        return false;
    }
    return true;
}
function canCancel(order){
    
	//内部件
    if(order.orderType=="6"){
        return false;
    }
    
    //对于下单失败、已取件、已取消不能进行取消操作
    var orderStateCode = order.orderStateCode;
    
    if(order.overDays >= 1 || orderStateCode == undefined || orderStateCode == '2' ||
        orderStateCode == '5' || orderStateCode == '7'){    
            return false;
    } else {
        return true;
    }
}

function canUrge(order){
    
    //内部件
    if(order.orderType=="6"){
        return false;
    }
    //嘿客自寄不能进行催单
    var orderSource=order.orderSource;
	if(orderSource.indexOf("HK") > -1){
		 return false;
	}
    //对于正在受理、下单失败、已取件、已取消不能进行催收操作
    var orderStateCode = order.orderStateCode;
    if(orderStateCode == undefined || orderStateCode == '0' || orderStateCode == '2' ||
        orderStateCode == '5' || orderStateCode == '7'){    
            return false;
    } else {
        return true;
    }
}

function canDelete(order){
    
    //内部件
    if(order.orderType=="6"){
        return true;
    }
    
    //对于正在受理、已受理、下单失败、已通知收派员取件、异常收件不能进行删除操作
    var orderStateCode = order.orderStateCode;
    if ((order.overDays >= 1 && "5" != orderStateCode) || "5" == orderStateCode || "7" == orderStateCode) {
        return true;
    } else {
        return false;
    }
}

/**关联运单号*/
function addWaybillNo(){
	var formdata  = $("#form_addWaybillNo").serialize();
	var url = '/service/order/myorder/waybill';
	var type = "POST";
	var dataType = 'JSON';
	asyncCallService(url, type, dataType, formdata, function(data) {
		if(data.flag == "success"){
			sfAlert(i18n.myorder_add_success);
		}else{
			sfAlert(i18n.myorder_add_fail);
		}
	}, function() {});
	
	addBnoDialog.close();
}
